﻿using System;
using System.Text;

namespace TcpAsyncServer
{
    class Program
    {
        /// <summary>
        /// all these callbacks have not access any instance, so totally state-less
        /// which is absolutely thread-safe
        /// </summary>
        //***********************************************//
        #region [ event callbacks ]
        static void OnAcceptedCallback(object source, AcceptEvtArgs evtargs)
        {
            EchoSocket acceptedSock = evtargs.EchoSock;
            Console.WriteLine("[++accept++] new client from <{0}>", acceptedSock.OwnedSocket.RemoteEndPoint.ToString());

            acceptedSock.ReceivedEvtHandler += OnReceivedCallback;
            acceptedSock.ClosedEvtHandler += OnClosedCallback;
        }

        static void OnReceivedCallback(object source, EchoEvtArgs evtargs)
        {
            string msg = Encoding.ASCII.GetString(evtargs.RecvBuffer, 0, evtargs.RecvLength);
            Console.WriteLine("[receive] from <{0}>,msg = {1}", evtargs.RecvSocket.RemoteEndPoint.ToString(), msg);
        }

        static void OnClosedCallback(object source, EchoEvtArgs evtargs)
        {
            Console.WriteLine("[--close--] client<{0}> is closed", evtargs.RecvSocket.RemoteEndPoint.ToString());
        }

        #endregion

        //***********************************************//
        #region [ main entry ]

        static void Main(string[] args)
        {
            TcpServer svr = new TcpServer();
            svr.AcceptedEvtHandler += OnAcceptedCallback;

            Console.WriteLine("the server is running, ... ...");
            svr.Start(6001);

            Console.ReadLine();

            svr.Dispose();
        }
        #endregion
    }
}
